package com.booleam.controller;

import com.alibaba.fastjson.JSON;
import com.booleam.model.ResponseDO;
import com.booleam.utils.LoggerUtil;
import com.booleam.utils.ResultCode;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author asen
 * @since 2016/11/25
 */
public class BaseController {

    protected String toJSON(ResponseDO response) {
        if(response == null) {
            response = new ResponseDO<String>(ResultCode.GLOBAL_FAILED, null, "服务器错误");
        }

        String data = JSON.toJSONString(response);
        LoggerUtil.logger.info(" Response ResultCode: " + response.getResultCode());
        LoggerUtil.logger.info(" Response Content:\n" + data);
        return data;
    }

    @ExceptionHandler
    @ResponseBody
    public String exceptionHandler(Exception e) {
        LoggerUtil.logger.debug("========================Exception========================");
        e.printStackTrace();
        LoggerUtil.logger.error(e);
        LoggerUtil.logger.debug("========================Exception========================");
        int code;
        String msg;
        if(e instanceof NumberFormatException) {
            code = ResultCode.GLOBAL_PARAM_ERROR;
            msg = "参数错误";
        } else {
            code = ResultCode.GLOBAL_FAILED;
            msg = "服务器错误";
        }

        ResponseDO result = new ResponseDO<String>(code, null, msg);
        return toJSON(result);
    }
}
